package com.dongdongshop.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.page.PageBeen;
import com.dongdongshop.pojo.TbAddress;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.CartService;
import com.dongdongshop.service.TbAddressService;
import com.dongdongshop.util.CookieUtils;
import com.dongdongshop.util.HttpClientGetDemo;
import com.dongdongshop.vo.Cart;
import org.apache.lucene.search.TotalHits;
import org.apache.shiro.SecurityUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("cart")
public class CartController {

    @Reference(timeout = 50000)
    private CartService cartService;


    @RequestMapping("JeepCart")
    public String JeepCart(){
        return "cart";
    }

    @Autowired
    private RestHighLevelClient client;

    @RequestMapping("addCart")
    public String addCart(HttpServletRequest request,HttpServletResponse response,Long itemId, Integer num) {
        if (itemId == 0 || num == 0){
            return "success-cart";
        }
        //未登录,1.先从cookie中查出来购物车的数据
        List<Cart> cartList = getCart(request,response);
        //2.保存到购物车
        cartList = cartService.addCart(cartList, itemId, num);
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            //3.重新放回到cookie中
            String cartListStr = JSONObject.toJSONString(cartList);//将list类型的数据转换为str类型,因为setCookie需要的是str类型
            CookieUtils.setCookie(request, response, "cartList", cartListStr, true);//true为编码相当于UTF-8
        } else {
            cartService.addCartToRedis(cartList, user.getUsername());
        }
        return "success-cart";
    }

    //1. 在先添加购物车的时候先查出来购物车里面还有什么内容
    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request, HttpServletResponse response) {
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();

        //从C  ookie中获取购物车的数据
        String cartListStr = CookieUtils.getCookieValue(request, "cartList", true);
        //判断cookie中是否为空(实用工具类)
        if (StringUtils.isBlank(cartListStr)) {
            cartListStr = "[]";
        }
        //转成对象
        List<Cart> cartListCookie = JSONObject.parseArray(cartListStr, Cart.class);

        if (user == null) {
            return cartListCookie;
        } else {
            List<Cart> cartListFromRedis = cartService.findCartListFromRed(user.getUsername());
            if (cartListCookie.size() > 0) {
                //合并购物车
                List<Cart> cartListMerage = cartService.merageCart(cartListFromRedis, cartListCookie);
                //并存到redis
                cartService.addCartToRedis(cartListMerage,user.getUsername());
                //删除cookie
                CookieUtils.deleteCookie(request, response, "cartList");
                return cartListMerage;
            }
            return cartListFromRedis;
        }

    }

    //分页
    @RequestMapping("getPage")
    public String getPage(@RequestParam(defaultValue = "1") Integer startIndex, @RequestParam(defaultValue = "10") Integer pageSize, String title, Model model) throws IOException {

        //1.构建SearchRequest请求对象,指定索引库
        SearchRequest searchRequest = new SearchRequest("dk2105");
        //2,构建SearchRequest查询对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //3 查询所有的
        MatchQueryBuilder builders = QueryBuilders.matchQuery("title", title);
        //4 将QueryBuilders 对象设置到SearchSourceBuilder中
        searchSourceBuilder.query(builders);
        //构建高亮HighlightBuilder高亮对象
        HighlightBuilder highlightBuilder = new HighlightBuilder();

        //设置高亮字段
        highlightBuilder.field("title");
        //设置高亮样式
        highlightBuilder.preTags("<font color='red'>");//前标签

        highlightBuilder.postTags("</font>");//尾标签
        //将高亮对象highlightBuilder设置到builder中
        searchSourceBuilder.highlighter(highlightBuilder);
        //将builder查询对象分装到请求对象request;
        /**
         * 通过sort方法指定排序规则
         * 第一个参数,排序字段
         * 第二个参数,升序还是降序(可以不填写默认升序)
         */
        searchSourceBuilder.from(startIndex);//起始页数

        searchSourceBuilder.size(pageSize);//每页条数

        searchRequest.source(searchSourceBuilder);

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        //获取总条数
        long total = response.getHits().getTotalHits().value;

        SearchHit[] hits = response.getHits().getHits();

        List<TbItem> items = new ArrayList<>();

        for (SearchHit hit : hits) {
            TbItem item = JSONObject.parseObject(hit.getSourceAsString(), TbItem.class);
            items.add(item);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("title");
            Text[] fragments = highlightField.getFragments();
            for (Text fragment : fragments) {
                item.setTitle(fragment.toString());
            }
        }
//        private Integer pageNum;
//        private Integer pageSize;
//        private Long total;
//        private List<T> rows;
//        private Integer pages;
        //总页数
        Long pages= total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        //当前页数
        int pageNum = startIndex /pageSize + 1;

        PageBeen pageBeen = new PageBeen(pageNum,pageSize,total,items,pages.intValue());

        List<Integer> list = userPageNumber(pageNum, pages.intValue());

        model.addAttribute("plist", list);

        model.addAttribute("page",pageBeen);

        model.addAttribute("title",title);

        return "search";
    }
    //分页公共方法
    public List<Integer> userPageNumber(Integer pageNum, Integer pages) {
        int b = 0;
        //每页显示10页，判断总页数 - 当前页 是否小于 0 ，如果小于说明展示页数不足十页则按照剩余页数循环
        if ((pages - pageNum) - 5 >= 0) {
            b = 5;
        } else {
            b = pages - pageNum;
        }
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= b; i++) {
            list.add(pageNum + i);
        }
        return list;
    }

    @RequestMapping("weather")
    @ResponseBody
    public Result weather() throws Exception {
        String url = "http://wthrcdn.etouch.cn/weather_mini";
        String param = "city";
        String value = "大同";
        String s = HttpClientGetDemo.httpGetByData(param, value, url);
        return Result.response(ResultEnum.SUCCESS).setData(s);
    }
}
